package org.jflame.captcha.validator;

import org.jflame.captcha.creator.Rect;

import java.util.ArrayList;

public class RectsVerifiable<T extends Rect> implements Verifiable<RectsVerifiable<T>> {

    private static final long serialVersionUID = 1L;

    private ArrayList<T> rects;

    public RectsVerifiable() {
    }

    public RectsVerifiable(ArrayList<T> rects) {
        this.rects = rects;
    }

    @Override
    public boolean verify(RectsVerifiable<T> intputPart) {
        if (this.rects.size() != intputPart.getRects()
                .size()) {
            return false;
        }
        Rect r;
        for (int i = 0; i < this.rects.size(); i++) {
            r = intputPart.getRects()
                    .get(i);
            if (!rects.get(i)
                    .inside(r.getX(), r.getY())) {
                return false;
            }
        }
        return true;
    }

    public ArrayList<T> getRects() {
        return rects;
    }

    public void setRects(ArrayList<T> rects) {
        this.rects = rects;
    }

    public void add(T rect) {
        if (rects == null) {
            rects = new ArrayList<>(4);
        }
        rects.add(rect);
    }

    public int size() {
        return rects == null ? 0 : rects.size();
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("RectsVerifiable [");
        if (rects != null) {
            builder.append("rects=");
            builder.append(rects);
        }
        builder.append("]");
        return builder.toString();
    }

}
